#!/bin/sh -e

okabi | (
  while read abi
  do
    rm -rf done test impl.o impl.c lib/$abi
    (
      echo getentropy
      echo getentropy2
      echo getrandom
      echo getrandom2
      echo getrandom3
      echo urandom
      echo backupforbenchmarkingnotsecure
    ) | (
      while read impl
      do
        okc-$abi | (
          while read c
          do
            [ -e done ] && continue
            echo "=== `date` === Trying $impl with $abi $c..." >&2
            rm -f test impl.o impl.c \
            && cp $impl.c impl.c \
            && $c -c impl.c \
            && $c -o test test.c impl.o \
            && killafter 1 ./test \
            && mkdir -p lib/$abi \
            && cp impl.o lib/$abi/kernelrandombytes.o \
            && touch done \
	    && echo "=== `date` === Success. Using $impl." >&2
          done
        )
      done
    )
  done
)

if [ ! -e done ]
then
  echo "=== `date` === No working kernelrandombytes for $abi." >&2
  exit 111
fi
